package com.pjb.springbootjjwt.store.storage.csv;

import com.pjb.springbootjjwt.store.File;
import com.pjb.springbootjjwt.store.Sql;
import com.pjb.springbootjjwt.store.entity.Error;
import com.pjb.springbootjjwt.store.entity.*;
import com.pjb.springbootjjwt.store.storage.Handler;
import com.pjb.springbootjjwt.store.utils.FileUtil;
import com.pjb.springbootjjwt.store.utils.RandomAccessFileUtil;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CSVHandlerImpl implements Handler {
    @Override
    public void crateTable(String table, String ddl) throws IOException {
        String path = FileUtil.getPath(table);
        FileUtil.write(path + ".frm", Define.toJson(ddl));
        FileUtil.write(path + ".csv", "");
    }

    @Override
    public void dropTable(String table) throws Exception {
        FileUtil.removeFile(table + ".csv");
        FileUtil.removeFile(table + ".frm");
    }

    @Override
    public void delete(String table, List<Line> list, List<Line> sub) throws Exception {
        if (sub.isEmpty()) {
            throw new Exception("" + Response.error.set(Error.E90003, table));
        }

        for (Line line : sub) {
            if (list.contains(line)) {
                int no = list.indexOf(line);
                PoiUtil.delete(table, no);
            }
        }
    }

    @Override
    public Record get(String table) throws IOException {
        String c = PoiUtil.read(table);
        String[] array = c.split(RandomAccessFileUtil.sp);
        List<Line> list = new ArrayList<>();
        if (array.length > 0)
            for (String lineStr : array) {
                if (!lineStr.trim().isEmpty()) list.add(PoiUtil.toLine(lineStr));
            }
        return Record.builder().line(list).build();//new Record(list);
    }

    @Override
    public void saveList(String table, List<Line> list) throws Exception {
        StringBuilder txt = new StringBuilder();
        for (Line line : list) {
            if (getIndex(table, line.getKey())) { //  主键冲突检测
                throw new Exception("" + Response.error.set(Error.E90002, table));
            }

            txt.append(PoiUtil.toText(line)).append(RandomAccessFileUtil.sp);
        }
        RandomAccessFileUtil.append(table + ".csv", txt.toString());
    }

    public boolean getIndex(String table, String key) throws IOException {
        String c = FileUtil.read(table + ".csv");
        String[] arr = c.split(RandomAccessFileUtil.sp);
        String ddl = File.getInstance().getDDL(table);
        int pkIndex = Sql.getInstance().getPKIndex(ddl);

        for (String lineStr : arr) {
            if (!StringUtils.isEmpty(lineStr)) {
                String[] fieldArr = lineStr.split(",");
                String pk = fieldArr[pkIndex];
                if (pk.equals(key)) return true;
            }
        }
        return false;
    }
}
